package biz

import (
	"context"
	"time"

	"lianzi_gos/internal/mods/mpweixin/dal"
	"lianzi_gos/internal/mods/mpweixin/schema"
	"lianzi_gos/pkg/errors"
	"lianzi_gos/pkg/util"
)

// banner management
type Staff struct {
	Trans  *util.Trans
	StaffD *dal.Staff
}

// Query banners from the data access object based on the provided parameters and options.
func (a *Staff) Query(ctx context.Context, params schema.StaffQueryParam) (*schema.StaffQueryResult, error) {
	params.Pagination = true

	result, err := a.StaffD.Query(ctx, params, schema.StaffQueryOptions{
		QueryOptions: util.QueryOptions{
			OrderFields: []util.OrderByParam{
				{Field: "created_at", Direction: util.DESC},
			},
		},
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

// Get the specified banner from the data access object.
func (a *Staff) Get(ctx context.Context, id string) (*schema.Staff, error) {
	banner, err := a.StaffD.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if banner == nil {
		return nil, errors.NotFound("", "Banner not found")
	}
	return banner, nil
}

// Create a new banner in the data access object.
func (a *Staff) Create(ctx context.Context, formItem *schema.StaffForm) (*schema.Staff, error) {
	staff := &schema.Staff{
		ID:        util.NewXID(),
		CreatedAt: time.Now(),
	}

	if err := formItem.FillTo(staff); err != nil {
		return nil, err
	}

	err := a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.StaffD.Create(ctx, staff); err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return staff, nil
}

// Update the specified banner in the data access object.
func (a *Staff) Update(ctx context.Context, id string, formItem *schema.StaffForm) error {
	banner, err := a.StaffD.Get(ctx, id)
	if err != nil {
		return err
	} else if banner == nil {
		return errors.NotFound("", "Banner not found")
	}

	if err := formItem.FillTo(banner); err != nil {
		return err
	}
	banner.UpdatedAt = time.Now()

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.StaffD.Update(ctx, banner); err != nil {
			return err
		}
		return nil
	})
}

// Delete the specified banner from the data access object.
func (a *Staff) Delete(ctx context.Context, id string) error {
	exists, err := a.StaffD.Exists(ctx, id)
	if err != nil {
		return err
	} else if !exists {
		return errors.NotFound("", "Banner not found")
	}

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.StaffD.Delete(ctx, id); err != nil {
			return err
		}
		return nil
	})
}
